package org.ants.basecomponent.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ants.basecomponent.pojo.menu.MenuInfo;
import org.ants.basecomponent.pojo.menu.MenuNode;
import org.ants.basecomponent.service.menu.MenuTreeService;
import org.ants.basecomponent.service.user.UserAuthService;
import org.ants.basecomponent.session.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 权限拦截器
 */
public class AuthInterceptor implements HandlerInterceptor {
    private static final String USER_AUTH_MENUS = "authMenus";
    private static final String USER_MENU_PATHS = "menuPaths";

    @Autowired
    private MenuTreeService menuTreeService;

    @Autowired
    private UserAuthService userAuthService;

    /**
     * 登录控制
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String requestUrl = httpServletRequest.getRequestURI()
                .replace(httpServletRequest.getContextPath(), "");
        UserInfo userInfo = (UserInfo) httpServletRequest.getSession().getAttribute("userInfo");
        if(userInfo==null){
        	return true;
        }
        List<Integer> userMenuIdList = userAuthService.getAuthMenuIds(userInfo.getUserName());
        List<MenuNode> menuNodeList = menuTreeService.getAuthMenuNodeList(userMenuIdList);
        MenuInfo menuInfo = menuTreeService.getAuthMenuInfo(requestUrl,menuNodeList);
        httpServletRequest.setAttribute(USER_MENU_PATHS,menuInfo.getMenuPaths());
        httpServletRequest.setAttribute(USER_AUTH_MENUS,menuInfo.getMenuList());
        return true;
    }


    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    /**
     * 异常处理
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @throws Exception
     */
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}
